import os
import pandas

#<in  date="2021-02-01T00:54:08.498" t="0"    >\x02 CBM1 VER:A1.08 SN:2226 0 0000 25000\r\n00000 0000 00000 0000 00000 0000 00000 0     0 0     0 0     0 0     0 0 //\r\n\x03G</in>
#<in  date="2021-01-12T07:54:13.159" t="2001" >\x01CL020215\x02\r\n40 00080 00130 ///// 00000000C080\r\n\x031b39\x04\r\n</in>

def cloudsort_ims4(x,y):
    for i in x:
        date = i[11:21]
        time = i[22:30]
        blower = i[74]
        base1 = i[90:95]
        base2 = i[101:106]
        base3 = i[112:117]
        vv = i[123:128]
        if base1 == "00000":
            base1 = ""
        else:
            base1 = str(float(base1)*0.3048)
        if base2 == "00000":
            base2 = ""
        else:
            base2 = str(float(base2)*0.3048)
        if base3 == "00000":
            base3 = ""
        else:
            base3 = str(float(base3)*0.3048)
        if vv == "00000":
            vv = ""
        else:
            vv = str(float(vv)*0.3048)
        m = date + " " + time + "," + base1 + "," +base2 + "," +base3 + "," +vv
        y.write(m)
        y.write('\n')

def cloudsort_avimet(x,y):
    for i in x:
        date = i[11:21]
        time = i[22:30]
        clouds = i[66]
        base1 = i[69:74]
        base2 = i[75:80]
        base3 = i[81:86]
        if clouds == "4":
            vv = base1
            reflectmax = base2
            # m = date + "," + vv
            # y.write(m)
            # y.write('\n')
        else:
            vv = ""
        if base1 == "00000" or base1 == "/////":
            base1 = ""
        if base2 == "00000" or base2 == "/////":
            base2 = ""
        if base3 == "00000" or base3 == "/////" :
            base3 = ""

        m = date + " " + time + "," + base1 + "," +base2 + "," +base3 + "," +vv

        y.write(m)
        y.write('\n')

def sortcsv(x,y):
    #读取文件数据
    df = pandas.read_csv(x)
    #按照列值排序
    data = df.sort_values(by="datetime" , ascending=True)
    #把新的数据写入文件
    data.to_csv(y, mode='a+', index=False)

if __name__ == '__main__':

    f1 = open(r'01_09CEILO.csv')
    f2 = open(r'02_09CEILO.csv')
    x1 = f1.readlines()
    x2 = f2.readlines()

    e = open('CEILO_09.csv',"w")
    n = 'datetime,base1,base2,base3,vv'
    e.write(n)
    e.write('\n')

    cloudsort_avimet(x1,e)
    cloudsort_avimet(x2,e)

    sortcsv('CEILO_09.csv', 'CEILO_09_sorted.csv')

